﻿using UnityEngine;
using System.Collections;
using Newtonsoft.Json;

public class CodecFactory 
{

   public static byte[] EncodeMessage(MessageRequest request)
    {
        int totalSize = MessageHeader.HeaderLength;
        byte[] bodyBytes = null;
        if(request.Body != null)
        {
            string body = JsonConvert.SerializeObject(request.Body);
            bodyBytes = System.Text.Encoding.UTF8.GetBytes(body);
            totalSize += bodyBytes.Length;
        }
        ByteBuf byteBuf = new ByteBuf(totalSize);
        MessageHeader header = request.Header;
        byteBuf.WriteInt(totalSize);
        byteBuf.WriteInt(header.SeqId);
        byteBuf.WriteInt(header.MessageId);
        byteBuf.WriteByte(header.MessageType);
        byteBuf.WriteLong(header.ClientSendTime);
        if(bodyBytes != null)
        {
            byteBuf.WriteBytes(bodyBytes);
        }
        return byteBuf.ToArray();
    }

    public static MessageResponse DecodeMessage(ByteBuf byteBuf)
    {
        MessageResponse response = new MessageResponse();
        MessageHeader header = new MessageHeader();
        response.Header = header;
        int totalSize = byteBuf.ReadInt();
        int messageId = byteBuf.ReadInt();

        int seqId = byteBuf.ReadInt();
        int messageType = byteBuf.ReadByte();
        
        long clientSendTime = byteBuf.ReadLong();
        long serverSendTime = byteBuf.ReadLong();
        header.MessageLength = totalSize;
        header.SeqId = seqId;
        header.MessageType = messageType;
        header.MessageId = messageId;
        header.ClientSendTime = clientSendTime;
        header.ServerSendTime = serverSendTime;
        if(byteBuf.ReadableBytes() > 0)
        {
            byte[] body = new byte[byteBuf.ReadableBytes()];
            byteBuf.ReadBytes(body);
            string json = System.Text.Encoding.UTF8.GetString(body);
            response.Body = json;
        }
        return response;
    }
}
